import React, { useState, useEffect, useRef } from 'react';
import './homePage.css';
import Header from '../Header/Header';
import { wechat } from '../../api';

// 导入 fj.png 作为背景图片
import roomImg from '../../assets/login/fj.png';

// 导入箱子区域的图片
import fzImg from '../../assets/login/fz.png';
import jqImg from '../../assets/login/jq.png';
import dxImg from '../../assets/login/dx.png';
import yImg from '../../assets/login/y.png';
import cmImg from '../../assets/login/cm.png';
import jpImg from '../../assets/login/jp.png';

/**
 * HomePage 页面组件
 * 功能：首页展示，自动调用微信登录和获取JS-SDK
 * @param {Function} onNextPage - 跳转到下一页的回调函数
 * @param {Function} onGoToTextPage - 跳转到textPage的回调函数
 */
const HomePage = ({ onNextPage, onGoToTextPage }) => {
  // 滑动检测状态
  const [touchStartY, setTouchStartY] = useState(0);
  const [touchEndY, setTouchEndY] = useState(0);
  
  // 微信相关状态
  const [isWechatLoading, setIsWechatLoading] = useState(false);
  const [wechatError, setWechatError] = useState(null);


  // 处理触摸开始
  const handleTouchStart = (e) => {
    setTouchStartY(e.touches[0].clientY);
  };

  // 处理触摸移动
  const handleTouchMove = (e) => {
    setTouchEndY(e.touches[0].clientY);
  };

  // 处理触摸结束 - 检测向上滑动
  const handleTouchEnd = () => {
    const swipeDistance = touchStartY - touchEndY;
    const minSwipeDistance = 50; // 最小滑动距离

    // 如果向上滑动距离足够大，则切换到下一页
    if (swipeDistance > minSwipeDistance && onNextPage) {
      onNextPage();
    }

    // 重置触摸位置
    setTouchStartY(0);
    setTouchEndY(0);
  };


  /**
   * 初始化微信相关功能
   * 功能：页面加载时直接调用微信登录接口
   */
  const initWechatServices = async () => {
    try {
      setIsWechatLoading(true);
      setWechatError(null);

      console.log('HomePage: 开始初始化微信服务...');
      const urlString = window.location.search;
      const userIdMatch = urlString.match(/[?&]userId=([^&]*)/);
      const userId = userIdMatch ? decodeURIComponent(userIdMatch[1]) : null;
      // 直接调用微信登录接口，传递两个空参数
      const loginResult = await wechat.login({ code: '123', state: userId });
      console.log('微信登录结果:', loginResult.userPhone);
      console.log('登录结果完整数据结构:', JSON.stringify(loginResult, null, 2));

      // 检查所有可能的 openId 位置并保存
      let savedOpenId = false;
      let savedUserId = false;

      // 尝试多种可能的数据结构
      const possibleOpenIds = [
        loginResult.data?.openId,
        loginResult.data?.openid,
        loginResult.openId,
        loginResult.openid,
        loginResult.data?.user?.openId,
        loginResult.data?.user?.openid
      ];

      const possibleUserIds = [
        loginResult.data?.userId,
        loginResult.data?.userid,
        loginResult.userId,
        loginResult.userid,
        loginResult.data?.user?.userId,
        loginResult.data?.user?.userid,
        loginResult.data?.id
      ];

      // 保存第一个非空的 openId
      for (const openId of possibleOpenIds) {
        if (openId && !savedOpenId) {
          localStorage.setItem('openId', openId);
          console.log('openId 已保存:', openId);
          savedOpenId = true;
          break;
        }
      }

      // 保存第一个非空的 userId
      for (const userId of possibleUserIds) {
        if (userId && !savedUserId) {
          localStorage.setItem('userId', userId);
          console.log('userId 已保存:', userId);
          savedUserId = true;
          break;
        }
      }

      if (!savedOpenId) {
        console.warn('警告：未找到 openId，登录结果:', loginResult);
        // 如果没有 openId，我们生成一个临时的用于测试
        const tempOpenId = 'temp_' + Date.now();
        localStorage.setItem('openId', tempOpenId);
        console.log('使用临时 openId:', tempOpenId);
      }

      if (!savedUserId) {
        console.warn('警告：未找到 userId，登录结果:', loginResult);
        // 如果没有 userId，我们生成一个临时的用于测试
        const tempUserId = 'user_' + Date.now();
        localStorage.setItem('userId', tempUserId);
        console.log('使用临时 userId:', tempUserId);
      }

      console.log('HomePage: 微信服务初始化成功');

    } catch (error) {
      console.error('HomePage: 微信服务初始化失败:', error);
      setWechatError(error.message || '微信服务初始化失败');
    } finally {
      setIsWechatLoading(false);
    }
  };
  
  // 组件挂载时初始化微信服务
  useEffect(() => {
    initWechatServices();
  }, []);
  
  // 组件挂载后3秒自动跳转，根据登录结果决定跳转目标
  useEffect(() => {
    const autoJumpTimer = setTimeout(async () => {
      try {
        // 从localStorage或直接调用登录接口获取userPhone
        const urlString = window.location.search;
        const userIdMatch = urlString.match(/[?&]userId=([^&]*)/);
        const userId = userIdMatch ? decodeURIComponent(userIdMatch[1]) : null;
        localStorage.setItem('userId', userId);

        console.log('准备重新调用登录接口获取userPhone...');
        const loginResult = await wechat.login({ code: '123', state: userId });
        console.log('登录接口完整响应:', loginResult);
        console.log('loginResult.userPhone:', loginResult.userPhone);
        console.log('loginResult.userPhone类型:', typeof loginResult.userPhone);

        const userPhone = loginResult.userPhone;
        console.log('检测到 userPhone:', userPhone, '类型:', typeof userPhone);
        console.log('HomePage: 3秒倒计时结束，根据userPhone决定跳转');
        console.log('onNextPage回调函数:', onNextPage);
        console.log('onGoToTextPage回调函数:', onGoToTextPage);

        console.log('开始判断userPhone值...');
        console.log('userPhone === 0:', userPhone === 0);
        console.log('userPhone === "0":', userPhone === '0');
        console.log('userPhone === 1:', userPhone === 1);
        console.log('userPhone === "1":', userPhone === '1');

        if (userPhone === 0 || userPhone === '0') {
          console.log('✅ 条件匹配: userPhone=0, 准备跳转到textPage');
          console.log('onGoToTextPage函数存在:', !!onGoToTextPage);
          if (onGoToTextPage) {
            console.log('🚀 执行跳转到textPage');
            onGoToTextPage();
          } else {
            console.error('❌ onGoToTextPage回调函数不存在');
          }
        } else if (userPhone === 1 || userPhone === '1') {
          console.log('✅ 条件匹配: userPhone=1, 准备跳转到packPage');
          console.log('onNextPage函数存在:', !!onNextPage);
          if (onNextPage) {
            console.log('🚀 执行跳转到packPage');
            onNextPage();
          } else {
            console.error('❌ onNextPage回调函数不存在');
          }
        } else {
          console.log('⚠️ userPhone未匹配任何条件，默认跳转到packPage');
          console.log('当前userPhone值:', userPhone, '类型:', typeof userPhone);
          if (onNextPage) {
            console.log('🚀 执行默认跳转到packPage');
            onNextPage();
          } else {
            console.error('❌ onNextPage回调函数不存在');
          }
        }
      } catch (error) {
        console.error('获取userPhone失败，默认跳转到packPage:', error);
        if (onNextPage) {
          onNextPage();
        }
      }
    }, 3000); // 3秒延迟

    return () => clearTimeout(autoJumpTimer);
  }, [onNextPage, onGoToTextPage]);

  return (
    <div
      className="room-page"
      style={{
        backgroundImage: `url(${roomImg})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        width: '100%',
        height: '100vh',
        position: 'relative'
      }}
    >
      <div
        className="room-page-content"
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
          {/* 顶部元素 */}
          <Header />


        

          {/* 箱子区域的图片动效 */}
          <div className="room-suitcase-area">
            <div className="room-floating-items">
              <img src={fzImg} alt="fz" className="room-floating-item item-3" decoding="sync" />
              <img src={jqImg} alt="jq" className="room-floating-item item-4" decoding="sync" />
              <img src={dxImg} alt="dx" className="room-floating-item item-2" decoding="sync" />
              <img src={yImg} alt="y" className="room-floating-item item-6" decoding="sync" />
              <img src={cmImg} alt="cm" className="room-floating-item item-1" decoding="sync" />
              <img src={jpImg} alt="jp" className="room-floating-item item-5" decoding="sync" />
            </div>
          </div>

          {/* 底部文字内容 */}
          <div className="room-bottom-text">
            <p className="room-bottom-line">2025年年度账单诗集</p>
            <div className='underline'></div>
            <p className="room-bottom-line">每一笔都是标记生活的韵脚</p>
            <p className="room-bottom-line">现在将回忆折叠，装进行走的方向</p>
          </div>

      </div>
    </div>
  );
};

export default HomePage;